package com.loukou.lkt.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alex.csvhelper.CsvWriteException;
import com.alex.csvhelper.CsvWriter;
import com.google.common.collect.Lists;
import com.loukou.lkt.lkt.bo.AllocationExportCsvBean;
import com.loukou.lkt.lkt.bo.AllocationOrderBo;
import com.loukou.lkt.lkt.bo.AllocationOrderSubmitBo;
import com.loukou.lkt.lkt.bo.PageList;
import com.loukou.lkt.lkt.entity.AllocationOrderDetail;
import com.loukou.lkt.lkt.resp.RespDto;
import com.loukou.lkt.lkt.service.AllocationOrderService;
import com.loukou.lkt.lkt.utils.FileUtil;
import com.loukou.lkt.web.processor.AllocationOrderProcessor;

@Controller
@RequestMapping("/allocation")
public class AllocationOrderController extends BaseController{
	@Autowired
	private AllocationOrderProcessor allocationOrderProcessor;
	
	@Autowired
	private AllocationOrderService allocationOrderService;
	
	@RequestMapping("index")
	public String index(){
		return "allocation/index";
	}
	
	@RequestMapping("edit")
	public ModelAndView edit(int orderId){
		ModelAndView mv = new ModelAndView("allocation/edit");
		String action = "新增";
		if(orderId >0){
			action = "编辑";
		}
		mv.addObject("curAction", action);
		return mv;
	}
	
	@RequestMapping("detail")
	@ResponseBody
	public ModelAndView detail(
			@RequestParam(value = "orderId", required = false, defaultValue = "0") int orderId,
			@RequestParam(value = "orderCode", required = false, defaultValue = "") String orderCode,
			@RequestParam(value = "outWarehouseName", required = false, defaultValue = "") String outWarehouseName,
			@RequestParam(value = "inWarehouseName", required = false, defaultValue = "") String inWarehouseName,
			@RequestParam(value = "hopeOutTime", required = false, defaultValue = "") String hopeOutTime,
			@RequestParam(value = "hopeInTime", required = false, defaultValue = "") String hopeInTime,
			@RequestParam(value = "allocationCost", required = false, defaultValue = "0.00") double allocationCost,
			@RequestParam(value = "remark", required = false, defaultValue = "") String remark){
		ModelAndView mv = new ModelAndView("allocation/detail");
		
		mv.addObject("orderCode", orderCode);
		mv.addObject("outWarehouseName", outWarehouseName);
		mv.addObject("inWarehouseName", inWarehouseName);
		mv.addObject("hopeOutTime", hopeOutTime);
		mv.addObject("hopeInTime", hopeInTime);
		mv.addObject("allocationCost", allocationCost);
		mv.addObject("remark", remark);
		return mv;
	}
	
	@RequestMapping(value="/getListData",method=RequestMethod.GET)
	@ResponseBody
	public RespDto<PageList<AllocationOrderBo>> getListData(
		@RequestParam(value = "orderCode", required = false, defaultValue = "") String orderCode,
		@RequestParam(value = "orderState", required = false, defaultValue = "-1") int orderState,
		@RequestParam(value = "outWarehouseId", required = false, defaultValue = "-1") int outWarehouseId,
		@RequestParam(value = "inWarehouseId", required = false, defaultValue = "-1") int inWarehouseId,
		@RequestParam(value = "outUserName", required = false, defaultValue = "") String outUserName,
		@RequestParam(value = "startCreateTime", required = false, defaultValue = "") String startCreateTime,
		@RequestParam(value = "endCreateTime", required = false, defaultValue = "") String endCreateTime,
		@RequestParam(value = "startOutTime", required = false, defaultValue = "") String startOutTime,
		@RequestParam(value = "endOutTime", required = false, defaultValue = "") String endOutTime,
		@RequestParam(value = "startInTime", required = false, defaultValue = "") String startInTime,
		@RequestParam(value = "endInTime", required = false, defaultValue = "") String endInTime,
		@RequestParam(value = "pageIndex", required = false, defaultValue = "1") int pageIndex,
		@RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize) {
        //登录人所属的仓库
		List<Integer> myWarehouseIds = getWarehosueIds();
		return allocationOrderProcessor.getAllocationOrderlst(orderCode, orderState, outWarehouseId,
				inWarehouseId, myWarehouseIds, outUserName,
				startCreateTime, endCreateTime, startOutTime,
				endOutTime, startInTime, endInTime, pageIndex, pageSize);
	}
	
	@RequestMapping(value="/detaillist",method=RequestMethod.GET)
	@ResponseBody
	public List<AllocationOrderDetail> getDetailsData(
		@RequestParam(value = "orderId", required = false, defaultValue = "0") int orderId,
		@RequestParam(value = "orderCode", required = false, defaultValue = "") String orderCode,
		@RequestParam(value = "outWarehouseId", required = false, defaultValue = "0") int outWarehouseId,
		@RequestParam(value = "inWarehouseId", required = false, defaultValue = "0") int inWarehouseId,
		@RequestParam(value = "hopeOutTime", required = false, defaultValue = "") String hopeOutTime,
		@RequestParam(value = "hopeInTime", required = false, defaultValue = "") String hopeInTime,
		@RequestParam(value = "allocationCost", required = false, defaultValue = "0.00") double allocationCost,
		@RequestParam(value = "remark", required = false, defaultValue = "") String remark) {
        if(orderId==0){
        	return null;
        }
        
		return allocationOrderProcessor.getDetails(orderId);
	}
	
	@RequestMapping(value="/save",method=RequestMethod.POST)
	@ResponseBody
	public RespDto<Object> save(@RequestBody AllocationOrderSubmitBo allocation) {
		//上线时sesstion中获取
		allocation.setOutuserid(1);
		allocation.setOutuserName("测试1");
		return allocationOrderProcessor.save(allocation);
	}
	
	@RequestMapping(value="/setOrderState",method=RequestMethod.GET)
	@ResponseBody
	public RespDto<Object> setOrderState(
		@RequestParam(value = "orderId", required = false, defaultValue = "0") int orderId,
		@RequestParam(value = "state", required = false, defaultValue = "") int state) {
        if(orderId==0){
        	return null;
        }
        
		return allocationOrderProcessor.saveState(orderId,state);
	}
	
	@RequestMapping("/sendToWms")
	@ResponseBody
	public RespDto<String> sendToWms(@RequestParam(value = "allocationOrderId", required = false, defaultValue = "") int allocationOrderId){
		RespDto<String> resp = new RespDto<String>();
		if(allocationOrderId <= 0){
			resp.setCode(201);
			resp.setResult("参数错误");
			return resp;
		}
		resp = allocationOrderService.sendAllocationOrderToWms(allocationOrderId);
		return resp;
	}
	
	@RequestMapping("exportCsv")
	public void exportCsv(
			@RequestParam(value = "orderCode", required = false, defaultValue = "") String orderCode,
			@RequestParam(value = "orderState", required = false, defaultValue = "-1") int orderState,
			@RequestParam(value = "outWarehouseId", required = false, defaultValue = "-1") int outWarehouseId,
			@RequestParam(value = "inWarehouseId", required = false, defaultValue = "-1") int inWarehouseId,
			@RequestParam(value = "outUserName", required = false, defaultValue = "") String outUserName,
			@RequestParam(value = "startCreateTime", required = false, defaultValue = "") String startCreateTime,
			@RequestParam(value = "endCreateTime", required = false, defaultValue = "") String endCreateTime,
			@RequestParam(value = "startOutTime", required = false, defaultValue = "") String startOutTime,
			@RequestParam(value = "endOutTime", required = false, defaultValue = "") String endOutTime,
			@RequestParam(value = "startInTime", required = false, defaultValue = "") String startInTime,
			@RequestParam(value = "endInTime", required = false, defaultValue = "") String endInTime, HttpServletResponse response){
		String downloadFilePath = FileUtil.getDownloadFilePath();
		String filename = "allocationOrderExport_" + (new Date().getTime()) + ".csv";
		String filePath = downloadFilePath + filename;
		List<Integer> myWarehouseIds = getWarehosueIds();
		RespDto<PageList<AllocationOrderBo>> pagelist = allocationOrderProcessor.getAllocationOrderlst(orderCode, orderState, outWarehouseId,
				inWarehouseId, myWarehouseIds, outUserName,
				startCreateTime, endCreateTime, startOutTime,
				endOutTime, startInTime, endInTime, 1, 1000);
		
		List<AllocationExportCsvBean> orderList =  Lists.newArrayList();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
		if(pagelist !=null && pagelist.getResult()!=null){
			for(AllocationOrderBo orderbo :pagelist.getResult().getEntityList()){
				AllocationExportCsvBean abean = new AllocationExportCsvBean();
				BeanUtils.copyProperties(orderbo, abean);
				if(orderbo.getCreateTime()!=null) abean.setCreateTime(sf.format(orderbo.getCreateTime()));
				if(orderbo.getOutTime()!=null) abean.setOutTime(sf.format(orderbo.getOutTime()));
				if(orderbo.getInTime()!=null) abean.setInTime(sf.format(orderbo.getInTime()));
				
				orderList.add(abean);
			}
		}
		
		CsvWriter<AllocationExportCsvBean> writer = new CsvWriter<AllocationExportCsvBean>(filePath, AllocationExportCsvBean.class);
		try {
			writer.start();
			if(orderList != null && orderList.size() > 0 ){
				try {
					writer.append(orderList);
				} catch (CsvWriteException e) {
					e.printStackTrace();
				}
			}
			writer.end();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		response.setContentType("application/vnd.ms-csv");     
		response.setCharacterEncoding("utf-8");
		response.setHeader("content-disposition", "attachment; filename="+filename);
		ServletOutputStream os;
		try {
			os = response.getOutputStream();
			File file = new File(filePath);
			InputStream is = new FileInputStream(file);
			byte[] byteArr = new byte[1024];
			byte[] bomStrByteArr = new byte[] { (byte) 0xef, (byte) 0xbb, (byte) 0xbf };
			os.write(bomStrByteArr);
			while(is.read(byteArr) > 0){
				os.write(byteArr);
			}
			is.close();
			file.delete();
			os.flush();
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
